<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="DID" prop="did">
        <el-input
          v-model="queryParams.did"
          placeholder="请输入DID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['access:device_access:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['access:device_access:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['access:device_access:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['access:device_access:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="device_accessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="DID" align="center" prop="did"/>
      <el-table-column label="DID类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.did_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="发布者" align="center" prop="issuer"/>
      <el-table-column label="起始日期" align="center" prop="validFrom" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validFrom, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="validUntil" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validUntil, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="访问控制树" align="center" prop="accessTree"/>
      <el-table-column label="访问类型" align="center" prop="accessType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.access_type" :value="scope.row.accessType"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="远程地址" align="center" prop="remoteAddress" show-overflow-tooltip/>-->
      <el-table-column label="密文" align="center" prop="cipher" show-overflow-tooltip/>
      <el-table-column label="是否上链" align="center" prop="onChain">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.on_chain" :value="scope.row.onChain"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['access:device_access:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['access:device_access:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备访问控制对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <!--        <el-form-item label="DID" prop="did">-->
        <!--          <el-input v-model="form.did" placeholder="请输入DID"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="设备DID" prop="did">
          <el-select v-model="form.did" placeholder="请选择" style="min-width: 260px">
            <el-option
              v-for="item in didList"
              v-if="item.type ===0"
              :key="item.did"
              :label="item.did+'  '+item.name"
              :value="item.did">
              <span style="float: left">{{ item.did }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起始日期" prop="validFrom">
          <el-date-picker clearable
                          v-model="form.validFrom"
                          type="date"
                          value-format="yyyy-MM-dd"
                          style="min-width: 260px"
                          placeholder="请选择起始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="validUntil">
          <el-date-picker clearable
                          v-model="form.validUntil"
                          type="date"
                          value-format="yyyy-MM-dd"
                          style="min-width: 260px"
                          placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="访问控制树" prop="accessTree">
          <el-input v-model="form.accessTree" placeholder="请输入访问控制树" disabled/>
          <div class="add-property-btn">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="openTreeLayer"
            >构造访问控制树
            </el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="访问类型" prop="type">
          <el-select v-model="form.accessType" placeholder="请选择访问类型" style="min-width: 260px">
            <el-option
              v-for="dict in dict.type.access_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="远程地址" prop="remoteAddress" v-if="form.accessType=== 1">
          <el-input
            v-model="form.remoteAddress"
            placeholder="请输入远程地址"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="秘密" prop="secret" v-if="form.accessType=== 0">
          <el-input v-model="form.secret" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改设备访问控制对话框 -->
    <el-dialog ref="treeDialog" :title="'访问控制树'" :visible.sync="openTree" append-to-body>
      <div>
        <org-tree
          :data="treeData"
          :props="defaultProps"
          :label-class-name="labelClass"
          :render-content="renderContent"
        />
        <div>
          <el-button type="primary" @click="saveTree">生成策略树</el-button>
          <el-button @click="resetTree">重置</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.el-tooltip__popper {
  max-width: 700px
}
</style>
<style>
.logic-node {
  background: #409eff;
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
}

.condition-node {
  background: #67c23a;
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
}

.node-box {
  display: flex;
  align-items: center;
  gap: 4px;
}

.el-button--text {
  color: black;
}

</style>

<script>

import {
  listDevice_access,
  getDevice_access,
  delDevice_access,
  addDevice_access,
  updateDevice_access
} from "@/api/device_access/device_access"
import OrgTree from "vue2-org-tree";
import "vue2-org-tree/dist/style.css";
import {
  getPropertyKeys,
  getPropertyValues,
} from "@/api/access_property/property";
import {list_did_all} from "@/api/user_access/user_access";

export default {
  name: "Device_access",
  dicts: ['did_type', 'on_chain', "access_type"],
  components: {OrgTree},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备访问控制表格数据
      device_accessList: [],
      didList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        did: null,
        type: null,
        issuer: null,
      },
      // 表单参数
      form: {
        did: "",
        validFrom: "",
        validUntil: "",
        accessTree: "",
        secret: "",
        accessType: 1,
        remoteAddress: "",
      },
      // 表单校验
      rules: {
        did: [
          {required: true, message: "DID不能为空", trigger: "blur"},
          {min: 10, message: 'DID不能少于10位', trigger: 'blur'}
        ]
      },
      treeData: {
        id: 1,
        label: "AND",
        type: "logic",
        children: [
          {
            id: 2,
            type: "condition",
            condition: {
              key: "",
              value: "",
            },
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      keyOptions: [],
      valueOptions: {},
      openTree: false,
    }
  },
  created() {
    this.getList()
    this.getAllDid()
  },
  methods: {
    /** 查询设备访问控制列表 */
    getList() {
      this.loading = true
      listDevice_access(this.queryParams).then(response => {
        this.device_accessList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getAllDid() {
      list_did_all().then((response) => {
        this.didList = response.data;
        console.log(this.didList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        did: null,
        type: null,
        issuer: null,
        validFrom: null,
        validUntil: null,
        accessTree: null,
        accessType: 1,
        remoteAddress: null,
        secret: null,
        cipher: null,
        onChain: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加设备访问控制"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDevice_access(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改设备访问控制"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice_access(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDevice_access(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除设备访问控制编号为"' + ids + '"的数据项？').then(function () {
        return delDevice_access(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('access/device_access/export', {
        ...this.queryParams
      }, `device_access_${new Date().getTime()}.xlsx`)
    },

    openTreeLayer() {
      this.openTree = true;
      this.loadKeys();
      this.expression = "";
      this.showExpression = false;
    },
    async loadKeys() {
      this.loadingKeys = true;
      this.keyError = null;
      try {
        const response = await getPropertyKeys();
        // 假设API返回的是字符串数组
        this.keyOptions = response.data.map((item) => ({
          label: item,
          value: item,
        }));
      } catch (error) {
        console.error("加载K值失败:", error);
        this.$message.error("加载K值失败，请检查网络连接");
      }
    },

    // 从API加载V值
    async loadValues(key) {
      this.loadingValues = true;
      try {
        const response = await getPropertyValues(key);
        // 假设API返回的是字符串数组
        this.$set(
          this.valueOptions,
          key,
          response.data.map((item) => ({
            label: item,
            value: item,
          }))
        );
      } catch (error) {
        console.error("加载V值失败:", error);
        this.$message.error("加载V值失败，请检查网络连接");
      }
    },

    // 给逻辑节点和条件节点加不同的样式
    labelClass(data) {
      return data.type === "logic" ? "logic-node" : "condition-node";
    },

    // 渲染每个节点的内容（自定义）
    renderContent(h, data) {
      if (data.type === "condition") {
        return (
          <div class="node-box">
            <el-select
              size="mini"
              value={data.condition.key}
              style="width: 110px"
              onInput={(v) => this.updateConditionKey(data, v)}
              placeholder="请选择类型"
            >
              {this.keyOptions.map((option) => (
                <el-option
                  label={option.label}
                  value={option.value}
                ></el-option>
              ))}
            </el-select>

            <el-select
              size="mini"
              value={data.condition.value}
              style="width: 110px"
              onInput={(v) => this.updateConditionValue(data, v)}
              placeholder="请选择值"
              filterable
              allow-create
            >
              {this.valueOptions[data.condition.key] &&
                this.valueOptions[data.condition.key].map((option) => (
                  <el-option
                    label={option.label}
                    value={option.value}
                  ></el-option>
                ))}
            </el-select>

            <el-button
              type="text"
              size="mini"
              onClick={() => this.addCondition(data)}
            >
              +
            </el-button>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.removeNode(data)}
            >
              -
            </el-button>
          </div>
        );
      } else {
        return (
          <div class="node-box">
            <el-select
              size="mini"
              value={data.label}
              style="width: 80px"
              onInput={(v) => (data.label = v)}
            >
              <el-option label="AND" value="AND"></el-option>
              <el-option label="OR" value="OR"></el-option>
            </el-select>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.addCondition(data)}
            >
              +条件
            </el-button>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.addGroup(data)}
            >
              +组
            </el-button>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.removeNode(data)}
            >
              -
            </el-button>
          </div>
        );
      }

    },

    // 更新条件节点的K值
    async updateConditionKey(node, key) {
      node.condition.key = key;
      // 重置值为空，因为K值改变了，V值也应该重新选择
      node.condition.value = "";

      // 如果这个K值的V值选项尚未加载，则从API加载
      if (key && !this.valueOptions[key]) {
        await this.loadValues(key);
      }
    },

    // 更新条件节点的V值
    updateConditionValue(node, value) {
      node.condition.value = value;
    },

    // 添加条件节点
    addCondition(parent) {
      if (!parent.children) this.$set(parent, "children", []);
      parent.children.push({
        id: Date.now(),
        type: "condition",
        condition: {
          key: "",
          value: "",
        },
      });
      this.$refs.treeDialog.doLayout()
    },

    // 添加逻辑分组
    addGroup(parent) {
      if (!parent.children) this.$set(parent, "children", []);
      parent.children.push({
        id: Date.now(),
        type: "logic",
        label: "AND",
        children: [],
      });
      this.$refs.treeDialog.doLayout()
    },

    // 删除节点
    removeNode(node) {
      // 根节点不能删
      if (node.id === this.treeData.id) {
        this.$message.error("根节点不能删除");
        return;
      }

      const findAndRemove = (target, parent) => {
        if (!parent.children) return;
        parent.children = parent.children.filter((c) => c.id !== target.id);
        parent.children.forEach((c) => findAndRemove(target, c));
      };
      findAndRemove(node, this.treeData);
      this.$refs.treeDialog.doLayout()
    },

    // 生成策略表达式
    generateExpression(data) {
      if (data.type === "condition") {
        return data.condition.key && data.condition.value
          ? `${data.condition.key}:${data.condition.value}`
          : "";
      } else {
        const childrenExpressions = data.children
          .map((child) => this.generateExpression(child))
          .filter((exp) => exp); // 过滤掉空表达式

        if (childrenExpressions.length === 0) return "";
        if (childrenExpressions.length === 1) return childrenExpressions[0];

        // 修复OR逻辑显示问题
        const operator = data.label.toLowerCase();
        return `(${childrenExpressions.join(` ${operator} `)})`;
      }
    },

    // 更新表达式
    updateExpression() {
      this.expression = this.generateExpression(this.treeData);
    },

    // 保存策略树
    saveTree() {
      this.updateExpression();
      this.showExpression = true;
      console.log("策略表达式：", this.expression);
      console.log("策略树结构：", JSON.stringify(this.treeData, null, 2));
      this.$message.success(`策略已保存: ${this.expression}`);
      this.form.accessTree = this.expression
      this.openTree = false
    },

    // 重置策略树
    resetTree() {
      this.treeData = {
        id: 1,
        label: "AND",
        type: "logic",
        children: [
          {
            id: 2,
            type: "condition",
            condition: {
              key: "",
              value: "",
            },
          },
        ],
      };
      this.expression = "";
      this.showExpression = false;
      this.$message.info("策略树已重置");
      this.$refs.treeDialog.doLayout()
    },
  }
}
</script>
